package com.erp.erp_ui.Department;

import com.erp.erp_dao.Department.IDepartmentDAO;
import com.erp.erp_entitys.Department.DepartmentEntity;
import com.erp.erp_entitys.Department.DepartmentExample;
import com.erp.erp_entitys.Department.DepartmentTreeEntity;
import com.erp.erp_entitys.LogDB.LogDBEntity;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_servers.Department.IDepartmentService;
import com.erp.erp_servers.log.ILogDBService;
import com.erp.erp_ui.base.Base;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.google.gson.internal.$Gson$Preconditions;
import com.ys.openapi.organization.department.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DepartmentControl
 * @Description 部门控制类
 * @Author songjizhen
 * @Date 2020-07-03 22:27
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "department")
 public class DepartmentControl extends Base {
    @Autowired
    IDepartmentService departmentService;
    @Autowired
    IDepartmentDAO departmentDAO;
    @Autowired
    ILogDBService logDBService;
    //云枢部门
    Department department=new Department();
    /**
     * 新增部门
     * @param record
     * @return
     */
    @RequestMapping(value = "insert",method = RequestMethod.POST)
    @ResponseBody

    public R<Integer> insert(@RequestBody DepartmentEntity record) {
        try {
            UserEntity user = (UserEntity )this.getBean("user");
            if(this.getExitBycode(record.getCode())){
                record.setCode(System.currentTimeMillis()+"");
            }
            record.setCompanyCode(departmentService.getCompanentcodeBycode(record.getPid()));
            record.setCreator(user.getCode());
            record.setCreateTime(new Date());
            int num = departmentService.insertSelective(record);
            List<Map> maps = departmentDAO.selectByPid(record.getPid());
            String path=maps.get(0).get("path").toString();
            int i = departmentDAO.updateByPid(record.getCode(), path+record.getCode());
            try {
                //开始与云枢同步
                //根据部门编码查询部门信息
                DepartmentExample example=new DepartmentExample();
                DepartmentExample.Criteria criteria = example.createCriteria();
                criteria.andCodeEqualTo(record.getPid());
                List<DepartmentEntity> departmentEntities = departmentService.selectByExample(example);
                String pname=departmentEntities.get(0).getName();

                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                com.ys.openapi.organization.entity.DepartmentEntity de=new com.ys.openapi.organization.entity.DepartmentEntity();
                de.setCorpId("main");
                de.setDeptType("YUNS_DEPT");
                de.setLeaf(true);
                de.setName(record.getName());
                de.setSourceid("CP"+sdf.format(new Date())+ Calendar.getInstance().get(Calendar.MILLISECOND));
                //de.setQueryCode("1_1#"+de.getSourceid());
                de.setParentId(pname);
                de.setDeleted(false);
                department.addDepartment(de);
                logDBService.insert(new LogDBEntity(user.getName()+"("+user.getCode()+")","insert(新增)","部门=>"+record.toString()));
                //结束
            } catch (Exception e ){
                num=num + 10000;
            }
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
           return  R.buildError(ResultStatusEnum.ERROR);
        }

    }
    /**
     * 根据id查询部门
     * @param id
     * @return
     */
    @RequestMapping(value = "selectByKey",method = RequestMethod.POST)
    @ResponseBody

    public  R<DepartmentEntity> selectByKey(Integer id) {
        try {
           DepartmentEntity departmentEntity = departmentService.selectByPrimaryKey(id);
            return R.build(departmentEntity);
        }catch (Exception e){
            e.printStackTrace();
          return  R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 根据id删除
     * @return
     */
    @RequestMapping(value = "deleteByKey",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> deleteByKey(Integer id){
        try {
            UserEntity user = (UserEntity )this.getBean("user");
            DepartmentEntity departmentEntity = departmentService.selectByPrimaryKey(id);
            int num = departmentService.deleteByPrimaryKey(id);
            try {
                //开始与云枢同步

                com.ys.openapi.organization.entity.DepartmentEntity departmentEntity2=new com.ys.openapi.organization.entity.DepartmentEntity();
                departmentEntity2.setParentId(departmentEntity.getName());
                departmentEntity2.setDeleted(true);
                departmentEntity2.setCorpId("main");
                departmentEntity2.setDeptType("YUNS_DEPT");
                departmentEntity2.setLeaf(true);
                departmentEntity2.setName(departmentEntity.getName());
                // de.setSourceid("CP"+sdf.format(new Date())+ Calendar.getInstance().get(Calendar.MILLISECOND));
                //de.setQueryCode("1_1#"+de.getSourceid());
                //de.setParentId(pname);
                //de.setDeleted(false);

                department.removeDepartment(departmentEntity2);
                logDBService.insert(new LogDBEntity(user.getName()+"("+user.getCode()+")","delete(删除)","部门=>"+id));
                //结束
            }catch (Exception e){
                num = num + 10000;
            }
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 根据id更新部门
     * @param record
     * @return
     */
    @RequestMapping(value = "update",method = RequestMethod.POST)
    @ResponseBody

    public R<Integer> update(@RequestBody DepartmentEntity record) {
        try {
            UserEntity user = (UserEntity )this.getBean("user");
            record.setCreator(user.getCode());
            record.setCreateTime(new Date());
            DepartmentEntity departmentEntity = departmentService.selectByPrimaryKey(record.getId());
            int num = departmentService.updateByPrimaryKeySelective(record);
            try {
                //开始与云枢同步
                String pname=departmentEntity.getName();
                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                com.ys.openapi.organization.entity.DepartmentEntity de=new com.ys.openapi.organization.entity.DepartmentEntity();
                de.setCorpId("main");
                de.setDeptType("YUNS_DEPT");
                de.setLeaf(true);
                de.setName(record.getName());
                // de.setSourceid("CP"+sdf.format(new Date())+ Calendar.getInstance().get(Calendar.MILLISECOND));
                //de.setQueryCode("1_1#"+de.getSourceid());
                de.setParentId(pname);
                de.setDeleted(false);
                department.updateDepartment(de);
                logDBService.insert(new LogDBEntity(user.getName()+"("+user.getCode()+")","update(更新)","部门=>"+record.toString()));
                //结束
            }catch (Exception e){
                num=num+10000;
            }

            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
           return  R.buildError(ResultStatusEnum.ERROR);
        }

    }
    /**
     * 根据给定的条件查询部门
     * @param
     * @return
     */
    @RequestMapping(value = "selectByPage",method = RequestMethod.POST)
    @ResponseBody

    public R<List<DepartmentEntity>> selectByPage(String id,String code,String pid,String name){
        try {
            DepartmentEntity record=new DepartmentEntity();
            List<DepartmentEntity> departmentEntities = departmentService.selectByExample(record);
            return R.build(departmentEntities);
        }catch (Exception e){
            e.printStackTrace();
           return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 获取组织机构树
     * @return
     */
    @RequestMapping(value = "selectTree",method = RequestMethod.POST)
    @ResponseBody
 
    public R<DepartmentTreeEntity> selectTree(){
        try {
            DepartmentTreeEntity departmentTreeEntity = departmentService.selectTree();
            return R.build(departmentTreeEntity);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 获取当前用户所属部门树
     * @return 当前用户所属部门树
     */
    @GetMapping("getCurrentUserDepartmentTree")
    @ResponseBody
    public R getCurrentUserDepartmentTree() {
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            DepartmentTreeEntity departmentTree = departmentService.getCurrentUserDepartmentTree(user.getDepartmentCode());
            return R.build(departmentTree);
        } catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    private boolean getExitBycode(String code){
        return departmentService.getExitBycode(code);
    }

    /**
     *
     * @param code  用户组编码
     * @param model  模块
     * @param lx  类型
     * @return
     */
    @RequestMapping(value = "selectUserTree",method = RequestMethod.GET)
    @ResponseBody
    public R<DepartmentTreeEntity> selectUserTree(String  code,String model,String lx){

        UserEntity user= (UserEntity)this.getBean("user");
        return R.build(departmentService.selectUserTree(code,model,lx,user.getCode()));
    }


    /**
     * 查询所有部门
     * @return
     */
    @RequestMapping("getAllDept")
    @ResponseBody
    public R getAllDept(){
        try {
            List<DepartmentEntity> departmentEntity = departmentService.selectByExample(new DepartmentEntity());
            return R.build(departmentEntity);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 获取所有用户所管理的部门
     * @return 所有用户所管理的部门
     */
    @GetMapping(value = "getAllDepartmentUser")
    @ResponseBody
    public R getAllDepartmentUser(){
        try {
            DepartmentTreeEntity departmentTree = departmentService.getAllDepartmentUser();
            return R.build(departmentTree);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

    }


    /**
     * 获取当前用户所管理的部门
     * @return 当前用户所管理的部门
     */
    @GetMapping(value = "getCurrentDepartmentUser")
    @ResponseBody
    public R getTheDepartmentManagedByTheCurrentUser(){
        try {
            UserEntity user = (UserEntity )this.getBean("user");
            DepartmentTreeEntity departmentTree = departmentService.getTheDepartmentManagedByTheCurrentUser(user.getCode());
            return R.build(departmentTree);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

    }

    /**
     * 获取当前用户所管理的部门(只包含在职人员)
     * @return 当前用户所管理的部门(只包含在职人员)
     */
    @GetMapping(value = "getServingOfficersDepartmentTree")
    @ResponseBody
    public R getServingOfficersDepartmentTree(){
        try {
            UserEntity user = (UserEntity )this.getBean("user");
            DepartmentTreeEntity departmentTree = departmentService.getServingOfficersDepartmentTree(user.getCode());
            return R.build(departmentTree);
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

    }
}
